import { conversationList } from '@/services/chat';
import {
  conversationAdd,
  requirementAdd,
  requirementProject,
} from '@/services/workBench';
import { useStoreWorkbench } from '@/store/workbench';
import {
  DownOutlined,
  MessageOutlined,
  SearchOutlined,
  UpOutlined,
} from '@ant-design/icons';
import { Collapse, Empty, Input, message, Tabs } from 'antd';
import moment from 'moment';
import React, { useCallback, useEffect, useState } from 'react';
import CreateModal from './CreateModal';
import styles from './index.less';

const { Panel } = Collapse;

const TabsArr = [
  { label: `CHAT列表`, key: `CHAT列表` },
  { label: `需求列表`, key: `需求列表` },
];

const Demand: React.FC = ({}) => {
  const { currentMenuItem } = useStoreWorkbench();
  const [tabKey, setTabKey] = useState<string>('CHAT列表');
  const [visibleModal, setVisibleModal] = useState(false);
  const [titleModal, setTitleModal] = useState('');
  const [chatList, setChatList] = useState<any>([]); // 对话列表
  const [requireList, setRequireList] = useState<any>([]); // 需求列表
  const [sortBy, setSortBy] = useState<boolean>(true); // true: 时间正序，false: 时间倒序
  const [timer, setTimer] = useState<any>(null);

  const init = async (description?: string) => {
    if (currentMenuItem?.requireId?.includes('未分类会话')) {
      return;
    }
    //  区分是项目，还是需求
    const params: any = {};
    if (currentMenuItem.menuType === '项目') {
      // 项目--
      params.projectId = currentMenuItem.projectId;
    }
    if (currentMenuItem.menuType === '需求') {
      // 需求--
      params.projectId = currentMenuItem.projectId;
      params.requirementId = currentMenuItem.requireId;
    }
    if (!params.projectId) return;
    // 查对话
    if (description) {
      params.description = description;
    }
    if (sortBy) {
      params.createdAtSort = 0;
    } else {
      params.createdAtSort = 1;
    }
    const { code, data } = await conversationList(params);
    if (code === 200 && data) {
      // 跟踪是否遇到 dayRange 为 1 的项
      let firstDayFlag = false;
      let secDayFlag = false;
      const arr = data.list.map((item: any) => {
        if (item.dayRange === 0 && !firstDayFlag) {
          firstDayFlag = true;
          return { ...item, dayNameSelf: '今天' }; // 添加 isfirstday 属性
        }
        if (item.dayRange === 1 && !secDayFlag) {
          secDayFlag = true;
          return { ...item, dayNameSelf: '昨天' }; // 添加 isfirstday 属性
        }
        return { ...item, isfirstday: null }; // 返回其他项不变
      });
      setChatList(arr);
    }
    // 查需求列表
    const res = await requirementProject(params.projectId);
    if (res.code === 200 && res.data) {
      if (params.requirementId) {
        const flag = res?.data?.find(
          (item: any) => String(item.id) === String(currentMenuItem.requireId),
        );
        setRequireList([{ ...flag }]);
      } else {
        setRequireList(res.data);
      }
    }
  };

  const handleSearch = useCallback((value: any) => {
    init(value);
  }, []);

  const handleChange = (e: { target: { value: any } }) => {
    const value = e.target.value;
    // 清除之前的定时器（如果有的话）
    if (timer) {
      clearTimeout(timer);
    }
    // 设置新的定时器，延迟 2 秒触发搜索
    const newTimer = setTimeout(() => {
      handleSearch(value);
    }, 1000); // 延迟 2 秒
    // 更新定时器
    setTimer(newTimer);
  };

  // useEffect(() => {
  //   if (currentMenuItem) {
  //     console.log('currentMenuItem===', currentMenuItem);
  //   }
  // }, [currentMenuItem]);

  console.log('chatList===', chatList);
  console.log('requireList===', requireList);
  console.log('currentMenuItem===', currentMenuItem);

  // 新建需求
  const onAddRequirement = async (values: any) => {
    await requirementAdd({
      projectId: currentMenuItem.id,
      title: values.title,
    });
    document.dispatchEvent(new CustomEvent('emitSearch'));
  };

  const onAddChat = async (values: any) => {
    if (currentMenuItem.id && values?.requirementId) {
      await conversationAdd({
        projectId: currentMenuItem.id,
        requirementId: values?.requirementId,
      });
      init();
    }
  };

  useEffect(() => {
    if (currentMenuItem) {
      init();
    }
  }, [currentMenuItem, sortBy]);

  return (
    <div className={styles['demand']}>
      <div className={`flex-between ${styles['header-wrap']}`}>
        <div className={`flex-left `}>
          <div
            className={`${styles['add-session']}`}
            onClick={() => {
              if (!currentMenuItem?.projectId) {
                message.error('请先选择项目');
                return;
              }
              setVisibleModal(true);
              setTimeout(() => {
                setVisibleModal(false);
              });
              setTitleModal('新建需求');
            }}
          >
            新建需求
          </div>
          <div
            className={`${styles['add-task']}`}
            onClick={() => {
              if (!currentMenuItem?.projectId) {
                message.error('请先选择项目');
                return;
              }
              setVisibleModal(true);
              setTimeout(() => {
                setVisibleModal(false);
                setTitleModal('新建对话');
              });
            }}
          >
            新建对话
          </div>
        </div>
        <div>
          <Input
            style={{ width: 600 }}
            size="middle"
            placeholder="模糊搜索"
            prefix={<SearchOutlined />}
            onChange={handleChange}
          />
        </div>
        <div
          className={`flex-between  ${styles['sort-time']}`}
          onClick={() => {
            setSortBy(!sortBy);
          }}
        >
          创建时间
          {sortBy ? (
            <DownOutlined style={{ marginLeft: 6, marginTop: 2 }} />
          ) : (
            <UpOutlined style={{ marginLeft: 6, marginTop: 2 }} />
          )}
        </div>
      </div>

      <div style={{ position: 'relative', paddingTop: 10 }}>
        <Tabs
          style={{
            position: 'absolute',
            top: -8,
            left: 0,
          }}
          activeKey={tabKey}
          type="card"
          items={TabsArr}
          onChange={(key) => setTabKey(key)}
        />
        <div style={{ marginTop: tabKey === 'CHAT列表' ? 30 : 10 }}>
          {tabKey === 'CHAT列表' &&
            (chatList && chatList.length > 0 ? (
              <>
                {chatList?.map((item: any) => {
                  return (
                    <div className={styles['list-box']} key={item?.id}>
                      {item?.dayNameSelf && (
                        <div className={styles['today-title']}>
                          {item?.dayNameSelf}
                        </div>
                      )}
                      <div className={`flex-between  ${styles['list-item']}`}>
                        <div className={`flex-between  ${styles['left-item']}`}>
                          <div className={styles['word-star']}>
                            <MessageOutlined
                              style={{
                                color: '#dc2e00',
                                marginRight: 8,
                                fontSize: 16,
                              }}
                            />
                            {item?.description || '新建会话'}
                            {item?.requirementName && (
                              <div className={styles['tag-star']}>
                                {item?.requirementName}
                              </div>
                            )}
                          </div>
                          <div style={{ color: '#6b7280' }}>
                            {moment(item?.createdAt).format('YYYY-MM-DD HH:mm')}
                          </div>
                        </div>
                        <div />
                      </div>
                    </div>
                  );
                })}
              </>
            ) : (
              <>
                <Empty style={{ marginTop: 100 }} />
              </>
            ))}
          {tabKey === '需求列表' &&
            (requireList && requireList.length > 0 ? (
              <>
                {requireList?.map((item: any) => {
                  return (
                    <Collapse
                      ghost
                      style={{ paddingTop: 24, marginBottom: -24 }}
                      key={item?.id}
                    >
                      <Panel
                        header={
                          <div style={{ fontWeight: 600 }}>{item?.title}</div>
                        }
                        key="1"
                      >
                        {item?.conversationDtoList?.length > 0 ? (
                          <>
                            <div className={styles['panel-content']}>
                              {item?.conversationDtoList?.map(
                                (items: any, index: number) => {
                                  return (
                                    <div
                                      key={index}
                                      className={`flex-between ${styles['panel-item']}`}
                                    >
                                      <div className={styles['word-star']}>
                                        {items?.description || '新建会话'}
                                      </div>
                                      <div style={{ color: '#6b7280' }}>
                                        {moment(items?.createdAt).format(
                                          'YYYY-MM-DD HH:mm',
                                        )}
                                      </div>
                                    </div>
                                  );
                                },
                              )}
                            </div>
                          </>
                        ) : (
                          <>
                            <Empty style={{ marginTop: 10 }} />
                          </>
                        )}
                      </Panel>
                    </Collapse>
                  );
                })}
              </>
            ) : (
              <>
                <Empty style={{ marginTop: 100 }} />
              </>
            ))}
        </div>
      </div>
      <CreateModal
        visibleModal={visibleModal}
        titleModal={titleModal}
        onAddRequirement={onAddRequirement}
        onAddChat={onAddChat}
      />
    </div>
  );
};

export default Demand;
